<?php
namespace Modules\Wx\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Modules\Wx\Entities\WxMenu;
use Modules\Wx\Http\Requests\WxMenuRequest;
class WxMenuController extends Controller
{
    //显示列表
    public function index()
    {
        $data = WxMenu::paginate(10);
        return view('wx::wx_menu.index', compact('data'));
    }

    //创建视图
    public function create(WxMenu $wx_menu)
    {
        return view('wx::wx_menu.create',compact('wx_menu'));
    }

    //保存数据
    public function store(WxMenuRequest $request,WxMenu $wx_menu)
    {
        //由于我们使用了模型中的$casts属性,所以在添加数据的时候,就要将post数据中的data数据转成json
        $post = $request->all();
        $post['data'] = json_decode($post['data'],true);
        $wx_menu->fill($post);
        $wx_menu->save();

        return redirect('/wx/wx_menu')->with('success', '保存成功');
    }

    //显示记录
    public function show(WxMenu $field)
    {
        return view('wx::wx_menu.show', compact('field'));
    }

    //编辑视图
    public function edit(WxMenu $wx_menu)
    {
        return view('wx::wx_menu.edit', compact('wx_menu'));
    }

    //更新数据
    public function update(WxMenuRequest $request, WxMenu $wx_menu)
    {
        $post = $request->all();
        $post['data'] = json_decode($post['data'],true);
        $wx_menu->update($post);
        return redirect('/wx/wx_menu')->with('success','更新成功');
    }

    //删除模型
    public function destroy(WxMenu $wx_menu)
    {
        $wx_menu->delete();
        return redirect('wx/wx_menu')->with('success','删除成功');
    }

    public function push(WxMenu $wx_menu,WechatService $wechatService){
        //调用wechat类里面的创建自定义菜单方法,来向微信服务器发请求,帮我们创建需要的菜单
        //调用创建菜单之前,需要设置配置项
        $res = $wechatService->instance('button')->create(['button' => $wx_menu['data']]);
//        $res = WeChat::instance('button')->create(['button' => $wx_menu['data']]);
        if ($res['errcode'] == 0){
            return back()->with('success','自定义菜单推送到微信成功,请打开手机微信公众号查看');
        }
        return back()->with('danger',$res['errmsg']);
    }
}